#define _DEFAULT_SOURCE

#include <math.h>
#include <stdio.h>
#include <string.h>

#define COMMAND_SIZE 128
#define RESPONCE_SIZE 2048
#define FLAGS_NUMBER 10

void run_test(char* filename);

int main() {
  run_test("test_files/1");
  run_test("test_files/2");
  run_test("test_files/3");
  return 0;
}

void run_test(char* filename) {
  char correct_responce[RESPONCE_SIZE] = "";
  char test_responce[RESPONCE_SIZE] = "";
  char correct_command[COMMAND_SIZE];
  char test_command[COMMAND_SIZE];
  int counter = 0;
  for (int i = 0; i < pow(2, FLAGS_NUMBER); i++) {
    // make command
    strcpy(correct_command, "cat");
    strcpy(test_command, "./s21_cat");
    char flag_str[FLAGS_NUMBER][32] = {"-b",
                                       "-e",
                                       "-n",
                                       "-s",
                                       "-t",
                                       "-E",
                                       "-T",
                                       "--number",
                                       "--squeeze-blank",
                                       "--number-nonblank"};
    for (int flag = 0; flag < FLAGS_NUMBER; flag++) {
      if ((i >> flag) & 1) {
        strcat(correct_command, " ");
        strcat(correct_command, flag_str[flag]);
        strcat(test_command, " ");
        strcat(test_command, flag_str[flag]);
      }
    }
    strcat(correct_command, " ");
    strcat(correct_command, filename);
    strcat(test_command, " ");
    strcat(test_command, filename);
    // run correct
    FILE* pf = popen(correct_command, "r");
    fread(correct_responce, sizeof(char), RESPONCE_SIZE, pf);
    pclose(pf);
    // run mine
    pf = popen(test_command, "r");
    fread(test_responce, sizeof(char), RESPONCE_SIZE, pf);
    pclose(pf);
    // result
    if (strcmp(test_responce, correct_responce) == 0) {
      counter++;
    } else {
      printf("Fail:\n");
      printf("correct command: %s\n", (correct_command));
      printf("correct data: %s\n", (correct_responce));
      printf("your command: %s\n", (test_command));
      printf("your data: %s\n", (test_responce));
    }
  }
  printf("File: %s, Correct tests: %d/%.0f\n", filename, counter,
         pow(2, FLAGS_NUMBER));
}